﻿@page "/playlists"
@using MusicX.Web.Shared.Playlists
@using MusicX.Web.Shared.Songs

<ErrorsList Errors="response?.Errors" />
<ErrorsList Errors="playlistSongsResponse?.Errors" />

<h1>Playlists</h1>

@if (this.response?.Data?.Playlists == null)
{
    <p><em>Loading...</em></p>
}
else if (!this.response.Data.Playlists.Any())
{
    <p><em>No playlists found.</em></p>
    <p><em>You can create a playlist by clicking on the "save" icon in the "Now playing" section.</em></p>
}
else
{
    foreach (var playlist in this.response.Data.Playlists)
    {
        <div class="card text-white bg-dark mb-3 d-inline-block" style="max-width: 18rem;">
            <div class="card-body">
                <h5 class="card-title">@playlist.Name</h5>
                <p class="card-text">
                    Songs: @playlist.SongsCount
                    <button class="btn btn-success" @onclick="() => PlayAll(playlist.Id)"><i class="fas fa-play"></i></button>
                    <button class="btn btn-secondary" @onclick="() => AddAll(playlist.Id)"><i class="fas fa-plus"></i></button>
                </p>
            </div>
        </div>
    }
}


@code {
    ApiResponse<GetAllPlaylistResponse> response;
    ApiResponse<GetSongsInPlaylistResponse> playlistSongsResponse;
    protected override async Task OnInitializedAsync()
    {
        this.response = await this.ApiClient.GetAllPlaylists();
    }

    private async Task PlayAll(int playlistId)
    {
        this.playlistSongsResponse = await this.ApiClient.GetSongsInPlaylist(playlistId);
        if (this.playlistSongsResponse.IsOk)
        {
            this.MediaPlayer.ClearPlaylist();
            foreach (var song in this.playlistSongsResponse.Data.Songs)
            {
                this.MediaPlayer.Add(song);
            }

            this.MediaPlayer.PlayNext();
        }
        else
        {
            this.StateHasChanged();
        }
    }

    private async Task AddAll(int playlistId)
    {
        this.playlistSongsResponse = await this.ApiClient.GetSongsInPlaylist(playlistId);
        if (this.playlistSongsResponse.IsOk)
        {
            foreach (var song in this.playlistSongsResponse.Data.Songs)
            {
                this.MediaPlayer.Add(song);
            }
        }
        else
        {
            this.StateHasChanged();
        }
    }
}
